﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;

namespace Chaks.SharePoint.Docs.ILP.Utilities
{
    public static class Extensions
    {
        /// <summary>
        /// ILPs the exists.
        /// </summary>
        /// <returns></returns>
        public static bool ILPExists(this SPWeb rootWeb,string listId)
        {
            SPList ilpList = rootWeb.GetList("/Lists/ILPSet/");

            SPListItem curItem = ilpList.Items.Cast<SPListItem>().FirstOrDefault(item => item["Title"].ToString() == listId);

            if (curItem != null)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Gets the ILP set item.
        /// </summary>
        /// <returns></returns>
        public static ILPSetItem GetILPSetItem(this SPWeb rootWeb, string listId)
        {
            ILPSetItem ilpSetItem=null;

            SPList ilpList = rootWeb.GetList("/Lists/ILPSet/");

            SPListItem curItem = ilpList.Items.Cast<SPListItem>().FirstOrDefault(item => item["Title"].ToString() == listId);

            if(curItem!=null)
            {
                ilpSetItem = new ILPSetItem
                                            {
                                                ListGuid = curItem["Title"].ToString(),
                                                EnableILP = curItem["EnableILP"].ToString()=="Yes" ? true:false,
                                                Groups = curItem["Groups"].ToString(),
                                                PermissionLevel = curItem["PermissionLevel"].ToString()
                                            };
            }

            return ilpSetItem;
        }

        /// <summary>
        /// Gets the ILP set item.
        /// </summary>
        /// <returns></returns>
        public static SPListItem GetILPSetListItem(this SPWeb rootWeb, string listId)
        {
            SPList ilpList = rootWeb.GetList("/Lists/ILPSet/");

            SPListItem curItem = ilpList.Items.Cast<SPListItem>().FirstOrDefault(item => item["Title"].ToString() == listId);

            return curItem;
        }

        /// <summary>
        /// Validates the field.
        /// </summary>
        /// <param name="listItem">The contact list item.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <returns><c>true</c> if [it is a valid field] [in the specified list item]; otherwise, <c>false</c>.</returns>
        public static bool ValidateField(this SPListItem listItem, string columnName)
        {
            if (listItem != null && !String.IsNullOrEmpty(columnName))
            {
                if ((listItem.Fields.ContainsField(columnName)) &&
                    (listItem[columnName] != null))
                {
                    return true;
                }

                return false;
            }

            return false;
        }

        /// <summary>
        /// Creates the list.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="listTemplateType">Type of the list template.</param>
        /// <param name="listName">Name of the list.</param>
        /// <param name="listDescription">The list description.</param>
        /// <param name="defaultListValues">The default list values.</param>
        /// <param name="enableVersioning">if set to <c>true</c> [enable versioning].</param>
        /// <param name="enableAttachments">if set to <c>true</c> [enable attachments].</param>
        /// <param name="searchable">if set to <c>true</c> [searchable].</param>
        /// <param name="showQuickLaunch">if set to <c>true</c> [show quick launch].</param>
        /// <param name="enableCTMgmt">if set to <c>true</c> [enable CT MGMT].</param>
        /// <returns></returns>
        public static Guid CreateList(this SPWeb web, SPListTemplateType listTemplateType, string listName,
            string listDescription, string[] defaultListValues, bool enableVersioning, bool enableAttachments, bool searchable, bool showQuickLaunch, bool enableCTMgmt)
        {
            // Overwrite custom list if it's already exist
            SPList targetList = (web.ListExists(listName)) ? web.Lists[listName] : null;

            if (targetList != null) // If list already exists, delete and recreate it.
            {
                web.Lists.Delete(targetList.ID);
            }

            // Create new list
            Guid newListId = web.Lists.Add(listName, listDescription, listTemplateType);

            // Assign list settings
            SPList newList = web.Lists[newListId];
            newList.EnableVersioning = enableVersioning;
            newList.EnableAttachments = enableAttachments;
            newList.NoCrawl = !searchable;
            newList.OnQuickLaunch = showQuickLaunch;
            newList.ContentTypesEnabled = enableCTMgmt;

            // Add custom list item values
            if (defaultListValues != null)
            {
                foreach (string defaultValue in defaultListValues)
                {
                    SPListItem newListItem = newList.Items.Add();
                    newListItem["Name"] = defaultValue;
                    newListItem["Title"] = defaultValue;
                    newListItem.Update();
                }
            }

            newList.Update();
            web.Update();

            return newListId;
        }

        /// <summary>
        /// Removes existing content types and assign new content types to a SPList
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="listName">Name of the list.</param>
        /// <param name="contentTypeName">Name of the content type.</param>
        public static void AssignContentTypeToList(this SPWeb web, string listName, string contentTypeName)
        {
            if (web.ListExists(listName))
            {
                SPList list = web.Lists[listName];

                // Get existing default content types
                SPContentTypeCollection originalContentTypes = list.ContentTypes;

                // Remove existing default content types
                foreach (SPContentType originalContentType in originalContentTypes)
                {
                    list.ContentTypes.Delete(originalContentType.Id);
                }

                // Assign new content type to list
                SPContentType newContentType = web.AvailableContentTypes[contentTypeName];
                list.ContentTypes.Add(newContentType);

                list.Update();
            }

        }

        /// <summary>
        /// Check whether Lists exists.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="name">The name of the SPList.</param>
        /// <returns><c>true</c> if [list exists]. Otherwise, <c>false</c>.</returns>
        public static bool ListExists(this SPWeb web, string name)
        {
            if (web != null && !String.IsNullOrEmpty(name))
            {
                return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, name));
            }

            return false;
        }

        /// <summary>
        /// Gets the site from the <paramref name="properties">feature receiver properties.</paramref>
        /// </summary>
        /// <param name="properties">The properties.</param>
        /// <returns></returns>
        public static SPSite GetSite(this SPFeatureReceiverProperties properties)
        {
            SPSite site = null;

            if (properties.Feature.Parent is SPWeb)
            {
                SPWeb spWeb = (SPWeb)properties.Feature.Parent;

                site = spWeb.Site;
            }
            else if (properties.Feature.Parent is SPSite)
            {
                site = (SPSite)properties.Feature.Parent;
            }

            return site;
        }

    }
}
